from flask import Flask, render_template, request, jsonify
import json
import os
from datetime import datetime, timedelta, timezone
import uuid

app = Flask(__name__)

# 数据文件路径
FEEDING_RECORDS_FILE = 'feeding_records.json'
GROWTH_EVENTS_FILE = 'growth_events.json'
SYSTEM_LOG_FILE = 'system_log.json'
CONFIG_FILE = 'config.json'

# 默认配置
DEFAULT_CONFIG = {
    'feeding_interval_hours': 3.5,
    'default_feeding_type': '瓶喂',
    'default_feeding_amount': '120ml',
    'version': 'V1.0.0'
}

# 创建东八区时区对象
TZ = timezone(timedelta(hours=8))

# 确保数据文件存在
def init_data_files():
    for file_path in [FEEDING_RECORDS_FILE, GROWTH_EVENTS_FILE, SYSTEM_LOG_FILE]:
        if not os.path.exists(file_path):
            with open(file_path, 'w', encoding='utf-8') as f:
                json.dump([], f)
    
    # 初始化配置文件
    if not os.path.exists(CONFIG_FILE):
        with open(CONFIG_FILE, 'w', encoding='utf-8') as f:
            json.dump(DEFAULT_CONFIG, f, ensure_ascii=False, indent=2)

# 读取数据
def load_data(file_path):
    with open(file_path, 'r', encoding='utf-8') as f:
        return json.load(f)

# 保存数据
def save_data(file_path, data):
    with open(file_path, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=2)

# 读取配置
def load_config():
    try:
        config = load_data(CONFIG_FILE)
        # 确保版本号存在
        if 'version' not in config:
            config['version'] = 'V1.0.0'
        return config
    except:
        # 如果配置文件损坏或不存在，使用默认配置
        save_data(CONFIG_FILE, DEFAULT_CONFIG)
        return DEFAULT_CONFIG

# 记录系统日志
def log_action(action, details, user_ip='localhost'):
    log_entry = {
        'timestamp': datetime.now(TZ).strftime('%Y-%m-%d %H:%M:%S'),
        'action': action,
        'user_ip': user_ip,
        'details': details
    }
    
    logs = load_data(SYSTEM_LOG_FILE)
    logs.append(log_entry)
    save_data(SYSTEM_LOG_FILE, logs)

# 主页路由
@app.route('/')
def index():
    return render_template('index.html')

# 获取配置
@app.route('/api/config')
def get_config():
    config = load_config()
    return jsonify(config)

# 更新配置
@app.route('/api/config', methods=['POST'])
def update_config():
    new_config = request.get_json()
    # 保留版本号
    current_config = load_config()
    new_config['version'] = current_config.get('version', 'V1.0.0')
    save_data(CONFIG_FILE, new_config)
    log_action('config_update', f'Updated config: {new_config}')
    return jsonify({'status': 'success'})

# 获取喂养记录
@app.route('/api/feeding')
def get_feeding_records():
    records = load_data(FEEDING_RECORDS_FILE)
    # 获取查询参数
    hours = request.args.get('hours', 48, type=int)
    if hours > 0:
        # 筛选最近指定小时的记录
        cutoff_time = datetime.now(TZ) - timedelta(hours=hours)
        # 为解析的时间添加时区信息以进行正确比较
        filtered_records = []
        for r in records:
            record_time = datetime.strptime(r['time'], '%Y-%m-%d %H:%M').replace(tzinfo=TZ)
            if record_time >= cutoff_time:
                filtered_records.append(r)
        records = filtered_records
    
    return jsonify(records)

# 记录喂养时间
@app.route('/api/feeding', methods=['POST'])
def record_feeding():
    data = request.get_json()
    new_record = {
        'id': str(uuid.uuid4()),
        'time': data.get('time', datetime.now(TZ).strftime('%Y-%m-%d %H:%M')),
        'type': data.get('type', '瓶喂'),
        'amount': data.get('amount', '120ml'),
        'note': data.get('note', '')  # 添加备注字段，默认为空字符串
    }
    
    records = load_data(FEEDING_RECORDS_FILE)
    records.append(new_record)
    save_data(FEEDING_RECORDS_FILE, records)
    
    log_action('feeding_record', f'Recorded feeding: {new_record}')
    
    return jsonify({'status': 'success', 'data': new_record})

# 更新喂养记录
@app.route('/api/feeding/<record_id>', methods=['PUT'])
def update_feeding_record(record_id):
    data = request.get_json()
    records = load_data(FEEDING_RECORDS_FILE)
    
    for record in records:
        if record['id'] == record_id:
            record['time'] = data.get('time', record['time'])
            record['type'] = data.get('type', record['type'])
            record['amount'] = data.get('amount', record['amount'])
            # 更新备注字段，如果请求中没有提供，则保持原有值
            record['note'] = data.get('note', record.get('note', ''))
            break
    
    save_data(FEEDING_RECORDS_FILE, records)
    log_action('feeding_update', f'Updated feeding record: {record_id}')
    
    return jsonify({'status': 'success'})

# 删除喂养记录
@app.route('/api/feeding/<record_id>', methods=['DELETE'])
def delete_feeding_record(record_id):
    records = load_data(FEEDING_RECORDS_FILE)
    records = [record for record in records if record['id'] != record_id]
    save_data(FEEDING_RECORDS_FILE, records)
    log_action('feeding_delete', f'Deleted feeding record: {record_id}')
    
    return jsonify({'status': 'success'})

# 获取成长事件
@app.route('/api/events')
def get_growth_events():
    events = load_data(GROWTH_EVENTS_FILE)
    # 获取查询参数
    days = request.args.get('days', 2, type=int)
    if days > 0:
        # 筛选最近指定天数的事件
        cutoff_date = datetime.now(TZ) - timedelta(days=days)
        # 为解析的时间添加时区信息以进行正确比较
        filtered_events = []
        for e in events:
            event_date = datetime.strptime(e['date'], '%Y-%m-%d').replace(tzinfo=TZ)
            if event_date >= cutoff_date:
                filtered_events.append(e)
        events = filtered_events
    
    return jsonify(events)

# 添加成长事件
@app.route('/api/events', methods=['POST'])
def add_event():
    data = request.get_json()
    new_event = {
        'id': str(uuid.uuid4()),
        'date': data.get('date', datetime.now(TZ).strftime('%Y-%m-%d')),
        'content': data.get('content', ''),
        'category': data.get('category', 'general')
    }
    
    events = load_data(GROWTH_EVENTS_FILE)
    events.append(new_event)
    save_data(GROWTH_EVENTS_FILE, events)
    
    log_action('event_added', f'Added event: {new_event}')
    
    return jsonify({'status': 'success', 'data': new_event})

# 更新成长事件
@app.route('/api/events/<event_id>', methods=['PUT'])
def update_event(event_id):
    data = request.get_json()
    events = load_data(GROWTH_EVENTS_FILE)
    
    for event in events:
        if event['id'] == event_id:
            event['date'] = data.get('date', event['date'])
            event['content'] = data.get('content', event['content'])
            event['category'] = data.get('category', event['category'])
            break
    
    save_data(GROWTH_EVENTS_FILE, events)
    log_action('event_update', f'Updated event: {event_id}')
    
    return jsonify({'status': 'success'})

# 删除成长事件
@app.route('/api/events/<event_id>', methods=['DELETE'])
def delete_event(event_id):
    events = load_data(GROWTH_EVENTS_FILE)
    events = [event for event in events if event['id'] != event_id]
    save_data(GROWTH_EVENTS_FILE, events)
    log_action('event_delete', f'Deleted event: {event_id}')
    
    return jsonify({'status': 'success'})

# 获取下次喂养时间
@app.route('/api/feeding/next')
def get_next_feeding():
    records = load_data(FEEDING_RECORDS_FILE)
    if not records:
        return jsonify({'status': 'no_data'})
    
    # 只考虑用于计算下一次喂养时间的类型：瓶喂、亲喂、奶粉
    feeding_types_for_calculation = ['瓶喂', '亲喂', '奶粉']
    feeding_records = [record for record in records if record['type'] in feeding_types_for_calculation]
    
    if not feeding_records:
        return jsonify({'status': 'no_feeding_data'})
    
    # 按时间排序，获取最新的记录
    feeding_records.sort(key=lambda x: datetime.strptime(x['time'], '%Y-%m-%d %H:%M'), reverse=True)
    
    now = datetime.now(TZ)  # 获取当前时间，并指定时区
    last_feeding_time = datetime.strptime(feeding_records[0]['time'], '%Y-%m-%d %H:%M').replace(tzinfo=TZ)

    # 从配置中获取喂养间隔
    config = load_config()
    interval_hours = config.get('feeding_interval_hours', 3.5)
    
    next_feeding_time = last_feeding_time + timedelta(hours=interval_hours)
    
    if now >= next_feeding_time:
        due = True
        remaining_minutes = 0
    else:
        due = False
        remaining_minutes = int((next_feeding_time - now).total_seconds() / 60)
    
    return jsonify({
        'last_feeding': last_feeding_time.strftime('%Y-%m-%d %H:%M'),
        'next_feeding': next_feeding_time.strftime('%Y-%m-%d %H:%M'),
        'due': due,
        'remaining_minutes': remaining_minutes,
        'interval_hours': interval_hours
    })

# 添加获取黄金价格的API接口
@app.route('/api/gold-prices')
def get_gold_prices():
    import requests
    import re
    
    url = "https://www.huilvbiao.com/api/gold_indexApi"
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36",
        "Referer": "https://www.huilvbiao.com/gold",
        "X-Requested-With": "XMLHttpRequest"
    }
    
    try:
        response = requests.get(url, headers=headers, timeout=10)
        response.encoding = "utf-8"
        content = response.text
        
        # 提取三种黄金价格数据
        gold_types = {
            "黄金延期": r'var hq_str_gds_AUTD="(.*?)";',
            "纽约黄金": r'var hq_str_hf_GC="(.*?)";',
            "伦敦金（现货黄金）": r'var hq_str_hf_XAU="(.*?)";'
        }
        
        result = {}
        for name, pattern in gold_types.items():
            match = re.search(pattern, content)
            if match:
                data = match.group(1).split(',')
                # 修正字段索引：
                # 0: 当前价格，7: 昨结算价，6: 时间，12: 日期
                current_price = data[0] if len(data) > 0 else "未知"
                last_settlement = data[7] if len(data) > 7 else "未知"
                # 处理空值（如纽约黄金的昨结算价可能为空）
                last_settlement = last_settlement if last_settlement else "无数据"
                # 组合更新时间
                update_time = f"{data[12]} {data[6]}" if len(data) > 12 and len(data) > 6 else "未知时间"
                
                # 计算涨幅（保留两位小数）
                try:
                    current = float(current_price)
                    last = float(last_settlement)
                    change = current - last
                    change_rate = (change / last) * 100 if last != 0 else 0
                    change_str = f"{change:.2f} ({change_rate:.2f}%)"
                except (ValueError, ZeroDivisionError):
                    change_str = "无法计算"
                
                result[name] = {
                    "当前价格": current_price,
                    "昨结算价": last_settlement,
                    "涨幅": change_str,
                    "更新时间": update_time
                }
            else:
                result[name] = {
                    "当前价格": "获取失败",
                    "昨结算价": "获取失败",
                    "涨幅": "无法计算",
                    "更新时间": "未知时间"
                }
        
        return jsonify(result)
    
    except Exception as e:
        print(f"获取数据失败：{str(e)}")
        return jsonify({"error": "获取黄金价格数据失败"}), 500

if __name__ == '__main__':
    init_data_files()
    app.run(debug=True,host='0.0.0.0',port=5003)